<template>
  <div class="txt-detail" ref="txtDetail">
    <div class="detail-header">
      <em>发布人：{{ detailInfo.userName }}</em>
      <em>发布时间：{{ detailInfo.publishTime | filterPublishTime }}</em>
      <em>内容类型：{{ detailInfo.contentType | filterContentType }}</em>
      <a href="javascript: void(0);" @click="transformImg">转换为图片</a>
    </div>
    <div class="detail-content" v-html="detailInfo.content"></div>
    <a-modal
      width="748px"
      title="文章转换为图片"
      :visible="visible"
      @cancel="visible = false"
    >
      <div slot="footer">
        <a-button type="primary" @click="visible = false">确定</a-button>
      </div>
      <img :src="dataURL" alt="图片" />
    </a-modal>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
export default {
  data () {
    return {
      detailInfo: {},
      visible: false,
      dataURL: ''
    }
  },
  methods: {
    async getActicleDetail () {
      const { id } = this.$route.query
      const res = await this.$http.get('/article/detail', { params: { id } })
      if (res.code === 200) {
        this.detailInfo = res.message
      }
    },
    async transformImg () {
      this.visible = true
      // 将html转换为canvas
      const canvas = await html2canvas(this.$refs.txtDetail, {
          // backgroundColor: null
      })
      // 将cnavas转换为base64的img的url格式
      this.dataURL = canvas.toDataURL("image/png")
    }
  },
  created () {
    this.getActicleDetail()
  }
}
</script>

<style scoped lang="less">
.txt-detail {
  width: 700px;
  border: 1px solid #eee;
  margin: 24px auto;
  padding: 10px;
  min-height: 860px;
  .detail-header {
    color: #bbb;
    font-size: 12px;
    em {
      margin-right: 24px;
    }
  }
  .detail-content {
    margin-top: 24px;
    text-indent: 24px;
    word-break: break-all;
  }
}
</style>